<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        function jsonp(url,params,callback){
            // 随机函数名 解决多个跨越请求的 函数名问题
            var funcName = 'jsonp_' + Date.now() + Math.random().toString().substr(2,5);
            
             // 将object的类型转换成String类型
             if (typeof params == 'object') {
                // 这里用字符串拼接速度慢 用数组
                var tmpArr = [];
                for(var key in params){
                    var value = params[key];
                    tmpArr.push(key + '=' + value);
                }
                // tmpArr ==> ['key1=value1','key2=value2'] 
                params = tmpArr.join('&');
                // params ==>  'key1=value1&key2=value2'
            }
            params = params || null;
            url += '?' + params;

            // 通过script发送get请求
            var script = document.createElement('script');
            script.src = url + '&callback=' + funcName;
            document.body.appendChild(script);

            // 设置回调函数
            window[funcName] = function(data){
                callback(data);

                // 执行完代码 就删除函数和script标签 不然dom里面会很多函数
                delete window[funcName];
                document.body.removeChild(script);
            }
            // 服务器返回js代码(函数)
        }

        jsonp('cross_origin.php',{id:1},function(res){
            console.log(res);
        });
        jsonp('cross_origin.php',{id:2},function(res){
            console.log("2222"+res);
        });
    </script>

</body>
</html>